import sys
import glob
import os.path
from PyQt4 import QtCore
from pluginsystem.plugin_system import get_all_plugins

def read_config_file(filename):
    result = {}
    name = os.path.splitext(os.path.split(filename)[1])[0]
    file = open(filename,"r")
    for line in file.readlines():
        if line.startswith("#"):
            continue
        tokens = line.split("=")
        tokens = [tok.strip() for tok in tokens]
        if len(tokens) == 2:
            result[tokens[0]] = tokens[1]
    return name,result


def get_config_files_in_dir(configdir):
    return glob.glob(os.path.join(configdir,"*.docv"))


def parse_all_configs():
    settings = QtCore.QSettings()
    configspath = str(settings.value("configs_path", QtCore.QVariant(QtCore.QString("./configs"))).toString())
    configfiles = get_config_files_in_dir(configspath)
    result = {}
    for file in configfiles:
        name, config = read_config_file(file) 
        result[name] = config
    return result

def build_node(config):
    node = []
    for plugin in get_all_plugins():
        if plugin._check(config):
            node.append(plugin.get_keyword())
    return node
        
def build_tree(configmap):
    result = {}
    for progname, config in configmap.items():
        result[progname] = build_node(config),config
    return result
        
def get_tree():
    configmap = parse_all_configs()
    return build_tree(configmap)